package com.ego.member.web;

import com.ego.common.constant.MemberConstant;
import com.ego.common.constant.SystemConstant;
import com.ego.common.exception.GlobalException;
import com.ego.common.util.Result;
import com.ego.common.vo.member.MemberVo;
import com.ego.member.service.MemberService;
import com.ego.member.vo.MemberLoginVo;
import com.ego.member.vo.MemberRegisterVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * @program: ego
 * @description: 登录注册
 * @author: KamTang
 * @create: 2022-12-20 14:03
 **/
@RestController
@RequestMapping("/member")
public class MemberWebController {

    @Autowired
    private MemberService memberService;

    /**
     * 注册
     */
    @PostMapping("/register")
    public Result register(@Valid @RequestBody MemberRegisterVo register) {
        try {
            memberService.register(register);
        } catch (GlobalException e) {
            return Result.error(e.getCode(), e.getMsg());
        }
        return Result.ok();
    }

    @PostMapping("/login")
    public Result login(@Valid @RequestBody MemberLoginVo login) {
        MemberVo member = memberService.login(login).toVo();
        if (ObjectUtils.isNotEmpty(member)) {
            return Result.ok().put(MemberConstant.LOGGED_USER, member);
        } else {
            return Result.error(SystemConstant.Status.ACCOUNT_PASSWORD_INVALID.getCode(),
                    SystemConstant.Status.ACCOUNT_PASSWORD_INVALID.getMsg());
        }
    }
}
